/*
 * @Author: jiu yin
 * @Date: 2023-04-03 11:14:22
 * @LastEditTime: 2023-05-10 16:19:16
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \init-admin\src\utils\request.js
 * jiu
 */


import axios from "axios";
import { getToken, setToken } from "@/utils/auth";
import router from "@/router";

// import md5 from "js-md5";




// create an axios instance
const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 30000, // request timeout
});

// request interceptor
service.interceptors.request.use(
    (config) => {
        // 内部token
        const token = getToken();
        config.headers["Authorization"] = `Bearer ${token}`;


        if (config.ContentType) {
            config.headers["Content-Type"] =
                "application/x-www-form-urlencoded";
        }
        if (config.responseType == "blob") {
            config.headers["responseType"] = "blob";
        }

        // TODO
        //  方便调试
        // if (config.url.indexOf('/admin/score') != -1) {
        // 	config.headers['instance_ip'] = '192.168.110.13';
        // } else {
        // 	config.headers['instance_ip'] = '192.168.110.48';
        // }
        // config.headers['instance_ip'] = '192.168.110.71:8097';
        return config;
    },
    (error) => {
        // do something with request error
        return Promise.reject(error);
    }
);

// response interceptor
service.interceptors.response.use(
    (response) => {
        const res = response.data;

        if (res.code == 200 && res.code !== undefined) {
            return res;
        } else {
            if (res.code === 500 || res.code === 400) {
                ElMessage({
                    message: res.message || "服务错误",
                    type: "error",
                    duration: 5 * 1000,
                });
            } else if (res.code === 401) {
                ElMessage({
                    message: "登录过期，请重新登录",
                    type: "error",
                    duration: 3 * 1000,
                    onClose: () => {
                        router.push("/login")
                    }
                });
            } else if (typeof res === "string" || res == undefined) {
                return Promise.reject(new Error(res || "Error"));
            } else {
                return res
            }
        }


    },
    (error) => {
        if (error.response?.status === 401 || error.response?.status === 400) {
            const router = useRouter();
            // token 过期了
            // 1、重置用户的状态
            // 2、用户跳转到 登录界面
            ElMessage({
                message: error.response.data.msg,
                type: "error",
                grouping: true,
                duration: 3 * 1000,
            });

        } else if (error.toString().includes("canceled")) {
            console.info("终止上一次请求");
        } else {
            ElMessage({
                message: "服务异常,请稍后重试",
                type: "error",
                grouping: true,
                duration: 3 * 1000,
            });
        }
        // return error
        return Promise.reject(new Error(error || "Error"));
    }
);
// get请求封装
// console.log(axios.defaults, "默认啊");

const request = (val) => {
    let { data, url, method, ContentType, responseType, type, hasToken, cancelToken, baseURL, onDownloadProgress, timeout } = val;

    if (method == "get" || method == "GET") {
        return service({
            baseURL,
            url,
            method,
            params: data,
            ContentType,
            responseType,
            cancelToken,
            onDownloadProgress,
            timeout
        });
    } else {
        return service({
            baseURL,
            url,
            method,
            data,
            ContentType,
            hasToken,
            responseType,
            cancelToken,
            onDownloadProgress,
            timeout
        });
    }
};

export default request;
